<?php

namespace App\Service;

use App\Model\ActiveJoinModel;
use App\Model\ActiveModel;
use App\Model\OrderModel;
use App\Model\UserModel;
use App\Utility\DataConversion;
use App\Utility\Payment;
use EasySwoole\ORM\Exception\Exception;
use Throwable;

class ActiveService extends BaseService
{
    /**
     * @param $is_hot
     * @param $limit
     * @param $page
     * @return array
     * @throws Exception
     * @throws Throwable
     */
    public function getList($is_hot, $limit, $page): array
    {
        if ($is_hot == 1) {
            $model = ActiveModel::create()->where(['is_deleted' => 0, 'is_hot' => 1]);
        } elseif ($is_hot == 0) {
            $model = ActiveModel::create()->where(['is_deleted' => 0, 'is_hot' => 0]);
        } else {
            $model = ActiveModel::create()->where(['is_deleted' => 0]);
        }
        $model->limit($limit * ($page - 1), $limit)->withTotalCount();
        $list = $model->order("id", "DESC")->all(['is_deleted' => 0]);
        $result = $model->lastQueryResult();
        // 总条数
        $total = $result->getTotalCount();

        if (empty($list)) {
            return [
                'result' => false,
                'msg' => '暂无活动'
            ];
        }

        $data = [];
        $time = time();
        foreach ($list as $item) {
            $data[] = [
                'id' => $item['id'],
                'title' => $item['title'],
                'free' => $item['type'],
                'price' => $item['price'],
                'join' => $item['join'],
                'limit' => $item['person'],
                'image' => $item['image'],
                'is_hot' => $item['is_hot'],
                'sponsor' => $item['sponsor'],
                'content' => $item['content'],
                'matter' => $item['matter'],
                'address' => $item['address'],
                'contact' => $item['contact'],
                'time' => date("Y-m-d H:i:s", $item['time']),
                'end_time' => date("Y-m-d H:i:s", $item['end_time']),
                'create_time' => date("Y-m-d H:i:s", $item['create_time']),
                'see' => $item['see'],
                'status' => $item['end_time'] < $time ? -1 : 0
            ];
        }

        return [
            'result' => true,
            'msg' => '获取成功',
            'data' => $data
        ];
    }

    /**
     * @param $uid
     * @param $gid
     * @return array
     * @throws Exception
     * @throws Throwable
     * @throws \EasySwoole\Mysqli\Exception\Exception
     */
    public function getDetail($uid, $gid): array
    {
        $active = ActiveModel::create()->getActive(['id' => $gid]);
        if (!$active) {
            return [
                'result' => false,
                'msg' => '该活动已结束'
            ];
        }

        $joins = ActiveJoinModel::create()->where(['gid' => $gid, 'status' => 1])->all();
        $users = [];
        if (!empty($joins)) {

            $uids = array_column($joins, 'uid');
            $users = UserModel::create()->where('id', $uids, "IN")->field('id, avatar')->all();
        }

        $status = 0;
        $join = ActiveJoinModel::create()->getActive(['gid' => $gid, 'uid' => $uid, 'status' => 1]);
        if ($join) $status = 1;
        $item = $active->toArray();
        $data = [
            'id' => $item['id'],
            'title' => $item['title'],
            'free' => $item['type'],
            'price' => $item['price'],
            'join' => $item['join'],
            'limit' => $item['person'],
            'is_hot' => $item['is_hot'],
            'sponsor' => $item['sponsor'],
            'content' => $item['content'],
            'matter' => $item['matter'],
            'address' => $item['address'],
            'contact' => $item['contact'],
            'image' => $item['image'],
            'time' => date("Y-m-d H:i:s", $item['time']),
            'end_time' => date("Y-m-d H:i:s", $item['end_time']),
            'create_time' => date("Y-m-d H:i:s", $item['create_time']),
            'see' => $item['see'],
            'status' => $status,
            'users' => $users
        ];

        return [
            'result' => true,
            'msg' => '获取成功',
            'data' => $data
        ];
    }

    /**
     * @param $uid
     * @param $gid
     * @param $num
     * @param $name
     * @param $tel
     * @return array
     * @throws Exception
     * @throws Throwable
     * @throws \EasySwoole\Mysqli\Exception\Exception
     */
    public function join($uid, $gid, $num, $name, $tel): array
    {
        $active = ActiveModel::create()->getActive(['id' => $gid]);
        if (!$active || $active->end_time < time()) {
            return [
                'result' => false,
                'msg' => '活动已结束'
            ];
        }

        if ($active->join >= $active->person && $active->person != 0) {
            return [
                'result' => false,
                'msg' => '人数已满'
            ];
        }

        $join = ActiveJoinModel::create()->getActive(['gid' => $gid, 'uid' => $uid]);
        if ($join && $join->status == 1) {
            return [
                'result' => false,
                'msg' => '您已参与该活动，请勿重复报名'
            ];
        }

        $par = [
            'uid' => $uid,
            'gid' => $gid,
            'num' => $num,
            'name' => $name,
            'tel' => $tel,
            'code' => DataConversion::getInstance()->get_random(6)
        ];

        $res = ActiveJoinModel::create()->addActive($par);
        if (!$res) {
            return [
                'result' => false,
                'msg' => '系统错误，请稍后重试'
            ];
        }

        return [
            'result' => true,
            'msg' => '参与成功',
            'data' => 'success'
        ];
    }

    /**
     * @param $uid
     * @param $gid
     * @param $price
     * @param $ip
     * @return array
     * @throws Exception
     * @throws Throwable
     * @throws \EasySwoole\Mysqli\Exception\Exception
     */
    public function confirmJoin($uid, $gid, $price, $ip): array
    {
        $join = ActiveJoinModel::create()->getActive(['gid' => $gid, 'uid' => $uid]);
        if ($join && $join->status == 1) {
            return [
                'result' => false,
                'msg' => '您已参与该活动，请勿重复报名'
            ];
        }
        $order_no = DataConversion::getInstance()->get_order_no();
        $name = "【活动报名】" . $order_no . '支付' . $price . '元';
        $orderParam = [
            'uid' => $uid,
            'rid' => $join->id,
            'type' => 4,
            'order_no' => $order_no,
            'amount_real' => $price,
            'payment_type' => 0,
            'status' => 3,
            'order_remark' => $name
        ];
        if ($price == 0) {
            $orderParam['status'] = 4;
            $orderParam['payment_real'] = 0.00;
            $orderParam['payment_amount'] = 0.00;
            $orderParam['payment_remark'] = 'SUCCESS';
            $orderParam['payment_status'] = 1;
            $orderParam['payment_time'] = time();
            $res = ActiveJoinModel::create()->update(['status' => 1], ['uid' => $uid, 'gid' => $gid]);
            if (!$res) {
                return [
                    'result' => false,
                    'msg' => '系统错误，请稍后重试'
                ];
            }
        } else {
            $appid = ConfigService::getInstance()->getSys("mxappid", 'wepay');
            $mxappid = ConfigService::getInstance()->getSys("mxminiappid", 'wepay');
            $mchid = ConfigService::getInstance()->getSys("mchid", 'wepay');
            $password = ConfigService::getInstance()->getSys("mxpassword", 'wepay');
            $cert = ConfigService::getInstance()->getSys("cert", 'wepay');
            $key = ConfigService::getInstance()->getSys("key", 'wepay');
            $notifyUrl = ConfigService::getInstance()->getSys("wenotify_url", 'wepay');
            $user = UserModel::create()->getUser(['id' => $uid]);
            if (!$user || $user->we_code == '') {
                return [
                    'result' => false,
                    'msg' => 'openidNotFound'
                ];
            }

            $res = Payment::getInstance()->mxWepay($appid, $mxappid, $mchid, $password, $cert, $key, $user->we_code, $order_no, $price * 100, $name, $notifyUrl, $ip);
            $result = $res->toArray();
        }

        $resOrder = OrderModel::create()->addOrder($orderParam);
        if (!$resOrder) {
            return [
                'result' => false,
                'msg' => '系统错误，请稍后重试'
            ];
        }

        return [
            'result' => true,
            'msg' => '成功',
            'data' => $result ?? 'success'
        ];
    }

    /**
     * @param $uid
     * @param $status
     * @return array
     * @throws Exception
     * @throws Throwable
     */
    public function getMyActive($uid, $status): array
    {
        $where = ['uid' => $uid];
        if ($status == 99) {
            $where['is_deleted'] = 0;
        } elseif ($status == -1) {
            $where['is_deleted'] = 1;
        } else {
            $where['status'] = 1;
            $where['complete'] = $status;
            $where['is_deleted'] = 0;
        }
        $acJoin = ActiveJoinModel::create()->where($where)->all();
        if (empty($acJoin)) {
            return [
                'result' => false,
                'msg' => '暂无数据'
            ];
        }

        $aid = array_column($acJoin, 'gid');

        $active = ActiveModel::create()->where('id', $aid, "IN")->all();
        $data = [];
        foreach ($acJoin as $a) {
            foreach ($active as $item) {
                if ($a['gid'] == $item['id']) {
                    $data[] = [
                        'id' => $item['id'],
                        'title' => $item['title'],
                        'free' => $item['type'],
                        'price' => $item['price'],
                        'join' => $item['join'],
                        'limit' => $item['person'],
                        'is_hot' => $item['is_hot'],
                        'sponsor' => $item['sponsor'],
                        'content' => $item['content'],
                        'matter' => $item['matter'],
                        'address' => $item['address'],
                        'contact' => $item['contact'],
                        'image' => $item['image'],
                        'time' => date("Y-m-d H:i:s", $item['time']),
                        'end_time' => DataConversion::getInstance()->timeToDate($item['end_time']),
                        'create_time' => date("Y-m-d H:i:s", $item['create_time']),
                        'see' => $item['see'],
                        'status' => $a['status'],
                        'status_label' => $a['status'] == 1 ? '已确认' : '未确认',
                        'complete' => $a['complete'],
                        'join_time' => date("Y-m-d H:i:s", $a['create_time']),
                        'num' => $a['num'],
                        'name' => $a['name'],
                        'tel' => $a['tel']
                    ];
                }
            }
        }

        return [
            'result' => true,
            'msg' => '获取成功',
            'data' => $data
        ];
    }

    /**
     * @param $uid
     * @param $id
     * @return array
     * @throws Exception
     * @throws Throwable
     * @throws \EasySwoole\Mysqli\Exception\Exception
     */
    public function removeMyActive($uid, $id): array
    {
        $res = ActiveJoinModel::create()->update(['is_deleted' => 1], ['uid' => $uid, 'gid' => $id]);
        if (!$res) {
            return [
                'result' => false,
                'msg' => '删除失败，请稍后重试'
            ];
        }

        return [
            'result' => true,
            'msg' => '操作成功',
            'data' => 'success'
        ];
    }

    /**
     * @param $uid
     * @param $id
     * @return array
     * @throws Exception
     * @throws Throwable
     * @throws \EasySwoole\Mysqli\Exception\Exception
     */
    public function getMyActiveDetail($uid, $id): array
    {
        $active = ActiveModel::create()->getActive(['id' => $id]);
        if (!$active) {
            return [
                'result' => false,
                'msg' => '活动已下线'
            ];
        }
        $item = $active->toArray();
        $data = [
            'id' => $item['id'],
            'title' => $item['title'],
            'free' => $item['type'],
            'price' => $item['price'],
            'join' => $item['join'],
            'limit' => $item['person'],
            'is_hot' => $item['is_hot'],
            'sponsor' => $item['sponsor'],
            'content' => $item['content'],
            'matter' => $item['matter'],
            'address' => $item['address'],
            'contact' => $item['contact'],
            'image' => $item['image'],
            'time' => date("Y-m-d H:i:s", $item['time']),
            'end_time' => DataConversion::getInstance()->timeToDate($item['end_time']),
            'create_time' => date("Y-m-d H:i:s", $item['create_time']),
            'see' => $item['see']
        ];
        $join = ActiveJoinModel::create()->getActive(['uid' => $uid, 'gid' => $id]);
        if (!$join || $join->status == 0) {
            $data['a_join'] = [];
        } else {
            $a = $join->toArray();
            $data['a_join'] = [
                'status' => $a['status'],
                'status_label' => $a['status'] == 1 ? '已确认' : '未确认',
                'complete' => $a['complete'],
                'join_time' => date("Y-m-d H:i:s", $a['create_time']),
                'num' => $a['num'],
                'name' => $a['name'],
                'tel' => $a['tel'],
                'code' => $a['code']
            ];
            $order = OrderModel::create()->getOrder(['uid' => $uid, 'rid' => $a['id'], 'type' => 4]);
            if ($order) $data['order'] = $order->toArray();
        }

        return [
            'result' => true,
            'msg' => '操作成功',
            'data' => $data
        ];
    }
}